/**
 * @ExecuteTick.as
 * 
 * @author sodaChen mail:asframe@qq.com
 * @version 1.0
 * <br>Copyright (C), 2010-2015 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:ASFrame
 * <br>Date:2016-5-6
 */
package com.asframe.tick
{
	import com.asframe.utils.VectorUtils;

	/**
	 * 心跳接口执行器
	 * @author sodaChen
	 * Date:2016-5-6
	 */
	public class ExecuteTick
	{
		public var tickCount			:int;
		private var tickList			:Vector.<ITick>;
		private var removeList			:Vector.<ITick>;
		private var removeCount			:int;
		private var isRunning			:Boolean;
		private var addList				:Vector.<ITick>;
		
		public function ExecuteTick()
		{
			tickList = new Vector.<ITick>();
			removeList = new Vector.<ITick>();
			addList = new Vector.<ITick>();
		}
		public function addTick(tick:ITick):void
		{
			if(isRunning)
			{
				addList.push(tick);
				return ;
			}
			tickList.push(tick);
			tickCount++;
			if(tickCount == 1)
			{
				Tick.addFun(calls);
			}
		}
		public function removeTick(tick:ITick):void
		{
			if(isRunning)
			{
				removeList.push(tick);
				removeCount++;
				return ;
			}
			VectorUtils.removeItem(tickList,tick);
			tickCount--;
			if(tickCount == 0)
			{
				Tick.removeFun(calls);
			}
		}
		public function clear():void
		{
			tickList.splice(0,tickList.length);
		}
		public function calls():void
		{
			isRunning = true;
			for (var i:int = 0; i < tickCount; i++) 
			{
				tickList[i].tick();
			}
			isRunning = false;
			if(removeCount > 0)
			{
				for (var j:int = 0; j < removeCount; j++) 
				{
					removeTick(removeList[j]);
				}
				removeCount = 0;
			}
			if(addList.length > 0)
			{
				for each (var tick:ITick in addList) 
				{
					addTick(tick);
				}
				addList.length = 0;
			}
		}
	}
}